package com.tstudy.laoshibang.weike;

import java.io.IOException;

import com.tstudy.laoshibang.utils.LogUtil;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;

public class VideoSurfaceView extends SurfaceView implements Callback, OnPreparedListener, OnCompletionListener {

	// 定义视频播放器
	private MediaPlayer videoPlayer = null;

	public VideoSurfaceView(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
		this.getHolder().addCallback(this);
		this.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
	}

	// 初始化视频播放器
	private void initVideoPlayer() throws IllegalArgumentException, IllegalStateException, IOException {

		videoPlayer = new MediaPlayer();
		videoPlayer.reset();
		videoPlayer.setDataSource("/sdcard/def.3gp");
		videoPlayer.setDisplay(this.getHolder());
		videoPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

		// 设置音量
		videoPlayer.setVolume(80, 100);
		// 设置播放预备侦听器
		videoPlayer.setOnPreparedListener(this);
		// 设置播放完成侦听器
		videoPlayer.setOnCompletionListener(this);
		videoPlayer.prepare();

		LogUtil.d(this.getClass().getSimpleName() + 
				"Width=" + videoPlayer.getVideoWidth() + ", height=" + videoPlayer.getVideoHeight());
	}

	// 播放完毕
	@Override
	public void onCompletion(MediaPlayer mp) {
		// TODO Auto-generated method stub
		if (videoPlayer != null) {
			videoPlayer.stop();
			videoPlayer.release();
			videoPlayer = null;
		}
	}

	// 播放已准备就绪
	@Override
	public void onPrepared(MediaPlayer mp) {
		// TODO Auto-generated method stub
		if (videoPlayer != null) {
			videoPlayer.start();
		}
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
		// TODO Auto-generated method stub

	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		// TODO Auto-generated method stub
		try {
			initVideoPlayer();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		// TODO Auto-generated method stub
		if (videoPlayer != null) {
			videoPlayer.release();
			videoPlayer = null;
		}
	}

}
